import {
	ProForm,
	ProFormCheckbox,
	ProFormDependency,
	ProFormDigit,
	ProFormInstance,
	ProFormList,
	ProFormRadio,
	ProFormSelect,
	ProFormText,
	ProFormDatePicker
} from "@ant-design/pro-components";
import DetailPageContainer from "../components/DetailPageContainer";
import styles from "./index.module.less";
import { useEffect, useRef, useState } from "react";
import { Col, Row, Space, Affix, Button, message, Radio, DatePicker } from "antd";
import useUrl from "@/hooks/useUrl";
import {
	deliverGoodsApi,
	getLogisticsCompanyAndIconList,
	getLogisticsCompanyList,
	getOrderDetail,
	onLineDeliverGoodsApi
} from "@/api/modules/transactionManagement";
import { useRequest } from "ahooks";
import Loading from "@/components/Loading";
import { isEmpty, filter, omit, map, some } from "lodash";
import ProductThumbnailName from "../components/ProductThumbnailName";
import Address from "../components/Address";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import { getReFundInfo } from "../Detail/OrderInformation/constant";
import FlowRadio from "./FlowRadio";
import dayjs from "dayjs";
import { DatePickerProps, RangePickerProps } from "antd/es/date-picker";

// 定义一个函数handleGetUserInfo，用于获取用户信息
export const handleGetUserInfo = (info: any) => {
	if (!info?.mobile) return "-";
	return `${info?.name}，${info?.mobile}，${info?.province}
	${info?.city}
	${info?.county}
	${info?.address}`;
};
export default () => {
	const formRef = useRef<ProFormInstance>();
	const [indeterminate, setIndeterminate] = useState(false);
	const [checkAll, setCheckAll] = useState(false);
	const [selectProducts, setSelectProducts] = useState<any[]>([]);
	const addressRef = useRef<any>();
	const { query, navigate } = useUrl();
	const order_id = query.get("order_id");
	const { data, loading, runAsync } = useRequest(() => getOrderDetail({ order_id }));
	const { loading: submitLoading, runAsync: submitRunAsync } = useRequest(deliverGoodsApi, { manual: true });
	const { loading: onLineSubmitLoading, runAsync: onLineSubmitRunAsync } = useRequest(onLineDeliverGoodsApi, { manual: true });
	const { data: deliveryData, runAsync: deliverRunAsync } = useRequest(getLogisticsCompanyAndIconList, { manual: true });

	const deliveryList = deliveryData?.data ?? [];

	const detailData = data?.data ?? {};

	useEffect(() => {
		if (!isEmpty(detailData.itemsList)) {
			formRef.current?.setFieldValue("itemsList", detailData.itemsList);
		}
	}, [detailData]);

	const handleAllCheckedChange = (checked: boolean) => {
		setCheckAll(checked);
		setIndeterminate(false);
		setSelectProducts(checked ? map(detailData?.itemsList, i => i?.spec_snapshot?.spec_id) : []);
	};

	//未发货的product
	const notDeliverProduct = filter(
		detailData?.itemsList,
		i => detailData?.order_have_send_spec_ids?.indexOf(i?.spec_snapshot?.spec_id) === -1
	);

	const handleProductCheckedChange = (id: number, checked: boolean) => {
		let selectProductsCopy = [...selectProducts];
		if (checked) {
			selectProductsCopy.push(id);
		} else {
			selectProductsCopy = filter(selectProductsCopy, i => i !== id);
		}
		setSelectProducts(selectProductsCopy);
		setIndeterminate(Boolean(selectProductsCopy.length) && selectProductsCopy.length < notDeliverProduct?.length);
		if (selectProductsCopy.length === notDeliverProduct?.length) {
			setCheckAll(true);
		} else {
			setCheckAll(false);

			// if(selectProductsCopy.length ===0){

			// }
		}
	};

	console.log("=========dddd:", detailData);

	//买家信息
	const receiverInfo = detailData?.receiver_info ?? {};

	//发货人信息
	const deliverInfo = detailData?.sender_info ?? {};

	//退货人信息
	const returnInfo = detailData?.return_info ?? {};

	useEffect(() => {
		deliverRunAsync(0);
	}, []);

	const handleValuesChange = (changeValues: any) => {
		if (Object.hasOwn(changeValues, "method")) {
			if (changeValues.method !== 1) {
				deliverRunAsync(changeValues.method === 3 ? 1 : 0);
				formRef.current?.setFieldValue("delivery", undefined);
				formRef.current?.setFieldValue("service_type", undefined);
				formRef.current?.setFieldValue("insuredCheckedValue", undefined);
				formRef.current?.setFieldValue("insuredCheckedValue_num", undefined);
			}
		}
		if (Object.hasOwn(changeValues, "delivery")) {
			formRef.current?.setFieldValue("service_type", undefined);
		}
	};

	const handleSubmit = () => {
		formRef.current?.validateFieldsReturnFormatValue?.()?.then(values => {
			console.log(values, '<============values')
			if (selectProducts.length === 0) {
				message.error("请选择发货商品");
				return;
			}
			if (!Boolean(deliverInfo?.shop_return_addresses_id)) {
				message.error("请选择发货地址");
				return;
			}
			if (!Boolean(returnInfo?.shop_return_addresses_id)) {
				message.error("请选择退货地址");
				return;
			}
			const { delivery } = values;

			let requestData = {
				...values,
				order_id,
				delivery_name: values?.delivery?.delivery_name,
				delivery_id: values?.delivery?.delivery_id,
				sender_address_id: deliverInfo?.shop_return_addresses_id,
				return_address_id: returnInfo?.shop_return_addresses_id,
				spec_ids: selectProducts
			};

			if (values?.method !== 1) {
				const deliveryTarget = deliveryList?.find(i => i?.biz_id === delivery?.biz_id);

				requestData = {
					...requestData,
					//保价金额
					insured_value: values?.insuredCheckedValue == 0 ? 0 : values.insuredCheckedValue_num,
					expect_time: values?.getPackageTime === 0 ? null : values?.expect_time,
					biz_id: delivery?.biz_id,
					delivery_name: delivery?.delivery_name,
					delivery_id: delivery?.delivery_id,
					service_name: deliveryTarget?.service_type?.find(i => i?.service_type === values?.service_type)?.service_name
				};
			}

			const api = values?.method === 1 ? submitRunAsync : onLineSubmitRunAsync;
			api(omit(requestData, ["itemsList", "delivery", "insuredCheckedValue", "getPackageTime"])).then(res => {
				if (res?.code === RESULT_CODES.SUCCESS) {
					navigate(-1);
					message.success("发货成功");
				}
			});
		});
	};

	// 获取当前时间
	const now = dayjs();
	// 获取三天后的时间
	const threeDaysLater = dayjs().add(3, "days");

	// 禁用不在当前时间到三天后之间的时间
	const disabledDate: RangePickerProps["disabledDate"] = current => {
		return current && (current < now.startOf("day") || current > threeDaysLater.endOf("day"));
	};
	// 禁用非整数小时的时间
	const disabledTime: DatePickerProps["disabledTime"] = current => {
		const disabledHour = [0, 1, 2, 3, 4, 5, 6, 7, 20, 21, 22, 23, 24];
		if (current && current.isSame(now, "day")) {
			// 如果是今天，禁用当前时间之前的小时
			return {
				disabledHours: () => {
					const hours = [...disabledHour];
					for (let i = 0; i < now.hour(); i++) {
						if (!some(disabledHour, v => v === i)) {
							hours.push(i);
						}
					}
					return hours;
				},
				disabledMinutes: () => [...Array(60).keys()].filter(i => i !== 0), // 禁用非整点分钟
				disabledSeconds: () => [...Array(60).keys()].filter(i => i !== 0) // 禁用所有秒
			};
		}
		return {
			disabledHours: () => disabledHour,
			disabledMinutes: () => [...Array(60).keys()].filter(i => i !== 0), // 禁用非整点分钟
			disabledSeconds: () => [...Array(60).keys()].filter(i => i !== 0) // 禁用所有秒
		};
	};

	return (
		<Loading isHeight100 loading={loading}>
			<DetailPageContainer className={styles.container} routeItem={{ title: "发货", className: styles.active }}>
				<ProForm onValuesChange={handleValuesChange} formRef={formRef} submitter={false} layout="horizontal">
					<div className={styles.title} style={{ paddingTop: 0 }}>
						1.确认订单信息
					</div>
					<div className={styles.information_box}>
						<Row className={styles.header}>
							<Col span={18}>
								<Space size={10} align="baseline">
									<ProFormCheckbox
										noStyle
										fieldProps={{
											onChange: e => handleAllCheckedChange(e.target.checked),
											checked: checkAll,
											indeterminate
										}}
									/>
									<div>订单号：{detailData?.order_id}</div>
								</Space>
							</Col>
							<Col span={6} className={styles.time}>
								支付时间：{detailData?.pay_time}
							</Col>
						</Row>
						<ProFormList
							name="itemsList"
							creatorButtonProps={false}
							copyIconProps={false}
							deleteIconProps={false}
							className={styles.list}
						>
							{(meta, index, action, count) => {
								const ProductItem = action.getCurrentRowData();
								const { label, hasBeenShipped } = getReFundInfo(detailData?.order_have_send_spec_ids, ProductItem);
								return (
									<Row className={styles.list_item}>
										<Col span={14}>
											<Space align="center" size={32}>
												<div style={{ width: "20px" }}>
													{!hasBeenShipped && (
														<ProFormCheckbox
															fieldProps={{
																checked: selectProducts.includes(ProductItem?.spec_snapshot?.spec_id),
																onChange: e => handleProductCheckedChange(ProductItem?.spec_snapshot?.spec_id, e.target.checked)
															}}
															noStyle
															name="checkedBoxName"
														/>
													)}
												</div>

												<div style={{ width: "400px" }}>
													<ProductThumbnailName data={[ProductItem ?? {}]} />
												</div>

												<div className={styles.list_num}>数量：{ProductItem?.spec_num}</div>
											</Space>
										</Col>
										<Col span={4} style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>
											<span>{label}</span>
										</Col>
										<Col span={6} className={styles.money_wrap}>
											<span className={styles.money}>￥{ProductItem?.format_spec_price}</span>
										</Col>
									</Row>
								);
							}}
						</ProFormList>
						<Space size={30} align="baseline" className={styles.footer}>
							<span className={styles.label}>买家收货信息</span>
							<span>{handleGetUserInfo(receiverInfo)}</span>
						</Space>
					</div>
					<div className={styles.title}>2.确认 发货/退货 信息</div>
					<div className={styles.deliveryInfo}>
						<Space direction="vertical" size={20}>
							<Space size={30}>
								<span className={styles.label}>我的发货信息</span>
								<Space size={20}>
									<span>{handleGetUserInfo(deliverInfo)}</span>
									<a onClick={() => addressRef.current?.onOpen("deliver", deliverInfo)}>修改</a>
								</Space>
							</Space>
							<Space size={30}>
								<span className={styles.label}>我的退货信息</span>
								<Space size={20}>
									<span>{handleGetUserInfo(returnInfo)}</span>
									<a onClick={() => addressRef.current?.onOpen("return", returnInfo)}>修改</a>
								</Space>
							</Space>
						</Space>
					</div>
					{/* <div className={styles.title}>3.选择发货方式</div> */}
					<div className={styles.title}>3.选择发货方式</div>
					<Space direction="vertical" size={10} className={styles.method}>
						<ProFormRadio.Group
							noStyle
							fieldProps={{
								optionType: "button",
								size: "large"
							}}
							initialValue={2}
							name="method"
							options={[
								// {
								// 	label: "自己联系物流",
								// 	value: 1
								// },
								{
									label: "在线下单",
									value: 2
								},
								{
									label: "散单现付",
									value: 3
								}
							]}
						/>
						<div className={styles.input_wrap}>
							<ProFormDependency name={["method"]}>
								{({ method }) => {
									if (method === 2 || method === 3) {
										return (
											<>
												<label className={styles.flow_title}>选择快递公司</label>
												<ProForm.Item name="delivery" rules={[{ required: true, message: "请选择" }]}>
													<FlowRadio list={deliveryList} />
												</ProForm.Item>
												<ProFormRadio.Group
													label="是否保价"
													name="insuredCheckedValue"
													rules={[{ required: true, message: "请选择" }]}
													fieldProps={{
														className: styles.free_shipping
													}}
													options={[
														{ label: "不保价", value: 0 },
														{
															label: (
																<Space size={20}>
																	<span>保价</span>
																	<ProFormDependency name={["insuredCheckedValue"]}>
																		{({ insuredCheckedValue }) => {
																			const isNot = insuredCheckedValue == 1;

																			return (
																				<ProFormDigit
																					placeholder={"请输入保价金额"}
																					name="insuredCheckedValue_num"
																					rules={[{ required: isNot, message: "" }]}
																					fieldProps={{
																						suffix: (
																							<>
																								<span style={{ lineHeight: "32px" }}>元</span>
																								<div className={styles.msg}>温馨提示：具体保价费用请参照各个快递公司的政策</div>
																							</>
																						),
																						disabled: !isNot
																					}}
																				/>
																			);
																		}}
																	</ProFormDependency>
																</Space>
															),
															value: 1
														}
													]}
												/>

												<ProFormDependency name={["delivery"]}>
													{({ delivery }) => {
														console.log("=========delivery_id:", delivery);

														if (isEmpty(delivery?.service_type)) return null;
														return (
															<ProFormRadio.Group
																label="服务类型"
																name="service_type"
																rules={[{ required: true, message: "请选择" }]}
																params={{ id: delivery?.biz_id }}
																request={async () => {
																	return map(delivery?.service_type, i => ({
																		...i,
																		label: i?.service_name,
																		value: i?.service_type
																	}));
																}}
															/>
														);
													}}
												</ProFormDependency>

												<ProFormRadio.Group
													label="揽件时间"
													name="getPackageTime"
													rules={[{ required: true, message: "请选择" }]}
													fieldProps={{
														className: styles.free_shipping
													}}
													options={[
														{ label: "已约定取件时间", value: 0 },
														{
															label: (
																<Space size={20}>
																	<span>期望上门时间</span>
																	<ProFormDependency name={["getPackageTime"]}>
																		{({ getPackageTime }) => {
																			const isNot = getPackageTime == 1;
																			return (
																				<div style={{ display: "flex", alignItems: "center" }}>
																					<ProFormDatePicker
																						name="expect_time"
																						format="YYYY-MM-DD HH:00" // 格式化显示
																						valueFormat="X"
																						onChange={(date: { startOf: (arg0: string) => any }) => {
																							if (date) {
																								const selectedTime = date.startOf("hour"); // 取整点时间
																								console.log("选择的时间：", selectedTime.valueOf());
																							}
																						}}
																						transform={(value) => {
																							// 将字符串转换为 dayjs 对象
																							return value ? dayjs(value, "YYYY-MM-DD HH:mm").valueOf() / 1000 : value;
																						}}
																						fieldProps={{
																							showTime: true,
																							format: "YYYY-MM-DD HH:00",
																							disabledDate: disabledDate,
																							disabledTime: disabledTime,
																							disabled: !isNot,
																							showNow: false, // 隐藏“此刻”按钮
																							// renderExtraFooter: () => "我的时间是"
																						}}
																					/>
																					<span style={{ marginLeft: 8, color: "#727272", fontSize: "12px" }}>
																						温馨提示: 顺丰散单必须指定时间，否则不会有收件员揽件
																					</span>
																				</div>
																			);
																		}}
																	</ProFormDependency>
																</Space>
															),
															value: 1
														}
													]}
												/>
											</>
										);
									}
									if (method === 3) {
										return (
											<ProForm.Item name="delivery" rules={[{ required: true, message: "请选择" }]}>
												<FlowRadio list={deliveryList} />
											</ProForm.Item>
										);
									}
									return (
										<Space size={10}>
											<ProFormText
												fieldProps={{
													style: { width: "260px" }
												}}
												placeholder={"请输入物流单号"}
												name="waybill_id"
												rules={[{ required: true, message: "" }]}
											/>
											<ProFormSelect
												fieldProps={{
													style: { width: "260px" },
													labelInValue: true,
													fieldNames: {
														label: "delivery_name",
														value: "delivery_id"
													}
												}}
												// placeholder={"如无法识别单号请手动选择"}
												placeholder={"请选择"}
												name="delivery"
												rules={[{ required: true, message: "" }]}
												request={async () => {
													const res = await getLogisticsCompanyList();

													return res?.data ?? [];
												}}
											/>
										</Space>
									);
								}}
							</ProFormDependency>
						</div>
					</Space>
					<Affix offsetBottom={0}>
						<div className={styles.submit_btn}>
							<Button type="primary" onClick={handleSubmit} loading={submitLoading || onLineSubmitLoading}>
								确认发货
							</Button>
						</div>
					</Affix>
				</ProForm>
				<Address ref={addressRef} shop_id={detailData?.shop_id} order_id={detailData?.order_id} updateDetail={runAsync} />
			</DetailPageContainer>
		</Loading>
	);
};
